

/**
 * Created with IntelliJ IDEA.
 * User: sandesh
 * Date: 09/09/13
 * Time: 1:05 PM
 * To change this template use File | Settings | File Templates.
 */


package com.twu.biblioteca;

import java.io.*;
import java.util.*;
import java.util.logging.Logger;

public class BibliotecaApp {

    private BooksLibraryController booksLibraryController;
    private MoviesLibraryController moviesLibraryController;
    private MemberController memberController;
    private Authenticator authenticator;
    private Logger logger;
    private BufferedReader reader;                 // For reading from the console

    final String BOOK_LIST_FILE="bookList.txt";    // source file containing the list of books
    final String MOVIE_LIST_FILE="movieList.txt";  // source file containing the list of movies
    final String MEMBER_LIST_FILE="memberList.txt";// source file containing the list of members
    final String LOG_FILE="errorLog.log";          // log file name
    final String ERROR_MESSAGE="Sorry,the system has encountered an error. Please try again later";

    String LOGGED_IN_USER="";
    boolean USER_HAS_LOGGED_IN=false;

    // constructor
    public BibliotecaApp()
    {
        logger=UtilityFunctions.getLogger(LOG_FILE,"errorLog");

        booksLibraryController=new BooksLibraryController(BOOK_LIST_FILE,logger);
        moviesLibraryController=new MoviesLibraryController(MOVIE_LIST_FILE,logger);
        memberController=new MemberController(MEMBER_LIST_FILE,logger);
        authenticator=new Authenticator(memberController,logger);

        try
        {
            reader=new BufferedReader(new InputStreamReader(System.in));
        }
        catch(Exception e)
        {
            System.out.println(ERROR_MESSAGE);
            logger.severe(e.toString());
            System.exit(1);
        }
    }

    public static void main(String[] args)
    {

        BibliotecaApp biblioteca=new BibliotecaApp();

        biblioteca.printWelcomeMessage();

        biblioteca.displayMenu();

        biblioteca.pollUser();

        biblioteca.printEndMessage();

        biblioteca.cleanUp();

    }

    void printWelcomeMessage()
    {
        System.out.println("Welcome to Biblioteca!");
    }

    void printEndMessage()
    {
        System.out.println("Thank you! Come again!");
    }

    void displayMenu()
    {
        System.out.println("MENU:");
        System.out.println("--------------------------------------------------------------");
        System.out.println("1.Login \n2.Display all books \n3.Reserve book \n4.Return book \n5.Display all movies \n6.Membership details \n7.Exit");
        System.out.println("--------------------------------------------------------------\n");
    }

    // This function polls the user for his/her options and performs the appropriate service
    void pollUser()
    {
        boolean done=false;
        do
        {
            int userOption=readOptionFromUser();

            switch(userOption)
            {
                case 1:
                    userLogin();
                    break;
                case 2:
                    booksLibraryController.displayAllBooksToConsole();
                    break;
                case 3:
                    booksLibraryController.reserveBookForMember(reader);
                    break;
                case 4:
                    booksLibraryController.returnBookFromMember(reader);
                    break;
                case 5:
                    moviesLibraryController.displayAllMoviesToConsole();
                    break;
                case 6:
                    membershipEnquiry();
                    break;
                case 7:
                    done=true;
                    break;
            }
        }while(!done);

    }

    void userLogin()
    {
        LOGGED_IN_USER=authenticator.authenticate(reader);
        if(LOGGED_IN_USER!=null)
            handleValidUser();
        else
            handleInvalidUser();
    }

    // Provides details about the member
    void membershipEnquiry()
    {
        if(!USER_HAS_LOGGED_IN)
            System.out.println("Please talk to a Librarian. Thank you!\n");
        else
        {
            memberController.printMemberDetailsToConsole(LOGGED_IN_USER);
        }
    }

    int readOptionFromUser()
    {
        int userOption=0;
        boolean gotValidOption=false;
        do {
            try
            {
                userOption=readUserOptionFromConsole();
            }
            catch(NumberFormatException e)
            {
                System.out.println("Please enter a valid option!\n");
                continue;
            }
            if(userOptionExceedsBounds(userOption))
            {
                System.out.println("Please enter a valid option!\n");
                continue;
            }
            gotValidOption=true;
        }while(!gotValidOption);

        return userOption;
    }

    void cleanUp()
    {
        booksLibraryController.saveBooksToFile();

        UtilityFunctions.cleanUpLogger(logger);
    }

    private boolean userOptionExceedsBounds(int option)
    {
        return ( !(option>0 && option<=7) );
    }

    private int readUserOptionFromConsole() throws NumberFormatException
    {
        int userOption=0;
        try
        {
            System.out.print("Please enter your option:");
            userOption=Integer.parseInt(reader.readLine());
        }
        catch(IOException e)
        {
            System.out.println(ERROR_MESSAGE);
            logger.severe(e.toString());
            System.exit(1);
        }
        return userOption;
    }

    private void handleValidUser()
    {
        USER_HAS_LOGGED_IN=true;
        System.out.println("You have been logged in successfully!\n");
    }

    private void handleInvalidUser()
    {
        System.out.println("The userId-password combination is incorrect\n");
    }


}
